package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.dto.TeachplanDTO;
import com.xuecheng.api.content.model.dto.TeachplanMediaDTO;
import com.xuecheng.api.media.model.agent.MediaClient;
import com.xuecheng.api.media.model.dto.MediaDTO;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.enums.content.TeachPlanEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.convert.TeachplanMediaConvert;
import com.xuecheng.content.entity.TeachplanMedia;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanMediaServiceImpl extends ServiceImpl<TeachplanMediaMapper, TeachplanMedia> implements TeachplanMediaService {

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private MediaClient mediaClient;

    @Autowired
    private CourseBaseService courseBaseService;


    //根据 课程ID 与 课程计划ID 查询 当前课程计划绑定的媒体资源
    public List<TeachplanMedia> getTeachPlanMedia(Long courseBaseId, Long teachPlanId) {
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId);
        queryWrapper.eq(TeachplanMedia::getCourseId,courseBaseId);
        List<TeachplanMedia> list = this.list(queryWrapper);
        return list;
    }

    //根据 媒资信息 查询 媒体资源是否绑定课程资源
    public Integer getTeachPlanMedia(Long mediaId) {
        if (ObjectUtils.isEmpty(mediaId)){
            ExceptionCast.cast(ContentErrorCode.E_120023);
        }
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getMediaId,mediaId);

        List<TeachplanMedia> list = this.list(queryWrapper);
        Integer size = list.size();

        return size;
    }

    /*课程计划绑定媒资信息
        关键信息 媒资ID,课程计划ID  不能为空
         业务数据
          课程计划是否存在  是否删除
          媒资信息是否存在 是否删除 审核状态是否为审核通过 是否为同一家机构
          课程基本信息 是否存在 是否删除审核状态：未提交、审核未通过 同一家机构
                否是录播课程（只有录播课程才可以绑定资源）
          判断课程计划是否已绑定媒资信息 绑定修改，未绑定添加
         添加/修改 绑定信息 判断是否成功
     */
    public TeachplanMediaDTO getTeachMediaDTO(TeachplanMediaDTO dto,Long companyID) {
        //媒资ID,课程计划ID
        Long mediaId = dto.getMediaId();
        Long teachplanId = dto.getTeachplanId();
        if (ObjectUtils.isEmpty(mediaId)||
        ObjectUtils.isEmpty(teachplanId)||
        ObjectUtils.isEmpty(companyID)){
            ExceptionCast.cast(ContentErrorCode.E_120023);
        }
        //课程计划是否存在  是否删除 是否为三级
        TeachplanDTO teachPlan = teachplanService.getTeachPlan(teachplanId);
        //判断是否是三级,不是三级不能绑定媒资信息
        Integer grade = teachPlan.getGrade();
        if (!TeachPlanEnum.THIRD_LEVEL.equals(grade)) {
            //不等于说明不是三级
            ExceptionCast.cast(ContentErrorCode.E_120410);
        }


        //媒资信息是否存在 是否删除 审核状态是否为审核通过(方法中以判断)
        RestResponse<MediaDTO> response = mediaClient.getById(mediaId);
        MediaDTO result = response.getResult();
        //判断 媒资信息 是否为同一家机构
        if (companyID.equals(result.getCompanyId())){
            ExceptionCast.cast(ContentErrorCode.E_120026);
        }

        //课程基本信息 是否存在 是否删除审核状态：未提交、审核未通过 同一家机构
        //是否是录播课程（只有录播课程才可以绑定资源）(方法那边已做判断)
        CourseBaseDTO courseBaseDTO = courseBaseService.queryCourseByID(teachPlan.getCourseId(), companyID);
        if (ObjectUtils.isEmpty(courseBaseDTO)){
            //不存在 说明不存在课程信息 或不符合条件
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }


        //课程计划是否已绑定媒资信息
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachplanId);
        List<TeachplanMedia> list = this.list(queryWrapper);


        TeachplanMedia teachplanMedia = TeachplanMediaConvert.INSTANCE.dto2entity(dto);

        if (!ObjectUtils.isEmpty(list)||list.size()>=1){
            //不为空，或长度大于等于1
            // 说明已绑定媒资信息 修改
            LambdaUpdateWrapper<TeachplanMedia> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TeachplanMedia::getTeachplanId,teachplanMedia.getId());
            updateWrapper.set(TeachplanMedia::getMediaId,mediaId);
            updateWrapper.set(TeachplanMedia::getMediaFilename,result.getFilename());
            updateWrapper.set(TeachplanMedia::getCourseId,courseBaseDTO.getCourseBaseId());
            boolean isUpdate = this.update(updateWrapper);
            //判断是否修改成功
            if (!isUpdate){
                ExceptionCast.cast(ContentErrorCode.E_120423);
            }
        }else {
            //说明没有 新增绑定媒资信息
            teachplanMedia.setCourseId(courseBaseDTO.getCourseBaseId());
            teachplanMedia.setMediaFilename(result.getFilename());
            boolean save = this.save(teachplanMedia);
            //判断是否添加成功
            if (!save){
                ExceptionCast.cast(ContentErrorCode.E_120411);
            }
        }

        TeachplanMediaDTO teachplanMediaDTO = TeachplanMediaConvert.INSTANCE.entity2dto(teachplanMedia);

        return teachplanMediaDTO;
    }
}
